<!-- 用户页面 -->
<template>
    <div class="box-max">
        <div class="box-top">
            <div class="box-log">
                <img style="height: 2.8rem;width: 2.8rem;" src="../assets/logo.png" alt="">
                <p>牛视频</p>
            </div>
            <div class="box-input">
                <div class="input bg-gray">
                    <input @keyup.enter="onInput" v-model="search" placeholder="请输入视频标题" class="search-s" type="text">
                    <div class="search-icon">
                        <font-awesome-icon @click="onInput" :icon="['fas', 'magnifying-glass']" />
                    </div>
                </div>
            </div>
            <div class="box-user-max">
                <el-button @click="open" v-if="!token" size="large" color="#626aef" type="primary">登 录</el-button>
                <div v-if="token" class="box-user-data">
                    <div>{{ userData.nickname }}</div>
                    <div>粉丝数 {{ store.followerCount }}</div>
                    <div>关注人数 {{ store.followCount }}</div>
                    <el-popover placement="top">
                        <p style="text-align: center;margin: 7px 0;">退出登录?</p>
                        <div style="text-align: center;">
                            <el-button size="small" text @click="visible = false">取消</el-button>
                            <el-button size="small" type="primary" @click="quitLogin">确定</el-button>
                        </div>
                        <template #reference>
                            <div>
                                <el-image @click="visible = true" class="user-image" :src="userData.avatar" fit="cover" />
                            </div>
                        </template>
                    </el-popover>
                </div>
            </div>
        </div>
        <div class="box-body">
            <div class="box-left">
                <div class="box-user">
                    <div class="option center">
                        <div class="center" :class="optionAc == 'video' ? 'option-ac' : 'option-nc'"
                            @click="onOption('video', 'video')"><font-awesome-icon class="icon"
                                :icon="['fas', 'ranking-star']" />推荐
                        </div>
                    </div>
                    <div class="option center">
                        <div class="center" :class="optionAc == 'followlist' ? 'option-ac' : 'option-nc'"
                            @click="onOption('followlist', 'followlist')"><font-awesome-icon class="icon"
                                :icon="['fas', 'user-check']" />关注</div>
                    </div>
                    <div class="option center">
                        <div class="center" :class="optionAc == 'collectlist' ? 'option-ac' : 'option-nc'"
                            @click="onOption('collectlist', 'collectlist')"><font-awesome-icon class="icon"
                                :icon="['fas', 'star']" />收藏
                        </div>
                    </div>
                    <div class="option center">
                        <div class="center" :class="optionAc == 'publish' ? 'option-ac' : 'option-nc'"
                            @click="onOption('publish', 'publish')"><font-awesome-icon class="icon"
                                :icon="['fas', 'upload']" />发布
                        </div>
                    </div>
                </div>
                <el-divider />
                <div class="box-sort">
                    <el-scrollbar class="scrollbar-option">
                        <div class="option center" v-for="(item, index) in optionArr" :key="index">
                            <div class="center options" @click="onOption(item.categoryId, 'videolist')"
                                :class="optionAc == item.categoryId ? 'option-ac' : 'option-nc'">
                                <div>
                                    <p>
                                        <span class="animation-left" v-if="optionAc == item.categoryId">{{ '->' }}</span>
                                        {{ item.categoryName }}
                                        <span class="animation-right" v-if="optionAc == item.categoryId">{{ '<-' }}</span>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
            </div>
            <div class="box-video">
                <router-view :parent-method="open"></router-view>
            </div>
        </div>
    </div>
    <!-- 遮罩 -->
    <div @click.stop="hideOverlay" class="overlay" ref="overflow"></div>
    <div ref="loginflow" class="box-login">
        <!-- --------------------- 登录弹窗 -------------------------------- -->
        <!-- 登录 -->
        <div class="login" v-if="!isRegister">
            <div class="login-l">
                <h1 class="title">牛视频</h1>
                <div class="inputs">
                    <div>
                        <p>用户名：</p>
                        <el-input v-model="username_login" placeholder="请输入用户名" />
                    </div>
                    <div>
                        <p>密码：</p>
                        <el-input v-model="password_login" type="password" placeholder="请输入密码" show-password />
                    </div>
                    <p style="margin-top: 0.3rem;">没有账号？立即 <span class="color-theme"
                            @click="onRegisterOrLogin('Register')">注册</span> 加入我们吧</p>
                    <div class="btns">
                        <el-button class="el-btn white-8" type="primary" size="large" @click="onLogin">登录</el-button>
                    </div>
                </div>
            </div>
            <div class="login-r">
                <Vue3Lottie class="login-lottie" ref="loginLottieContainer" :animationData="loginJson" height="100%"
                    width="55%" />
            </div>
        </div>

        <!-- 注册 -->
        <div class="login" v-if="isRegister">
            <div class="login-r">
                <Vue3Lottie class="login-lottie" ref="loginLottieContainer" :animationData="signInJson" height="100%"
                    width="55%" />
            </div>
            <div class="login-l">
                <h1 class="title">牛视频</h1>
                <div class="inputs">
                    <div>
                        <p>用户名：</p>
                        <el-input v-model="username" placeholder="请输入用户名" />
                    </div>
                    <div>
                        <p>密码：</p>
                        <el-input v-model="password" type="password" placeholder="请输入密码" show-password />
                    </div>
                    <div>
                        <p>确认密码：</p>
                        <el-input v-model="passwordConfirm" type="password" placeholder="请再次输入密码" show-password />
                    </div>
                    <p style="margin-top: 0.3rem;">已有账号?请使用您的账号进行 <span class="color-theme"
                            @click="onRegisterOrLogin('theme')">登录</span> </p>
                    <div class="btns">
                        <el-button type="primary" class="el-btn white-8" @click="onEnroll">注册</el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from "vue-router"
import { ref, onMounted } from 'vue'
import { register, login } from '@/apis/api/login';
import { categoryList, getUserInfo } from '@/apis/api/list';
import loginJson from '../assets/lottie/login.json';
import signInJson from '../assets/lottie/signin.json';

import { useCounterStore } from '../pinia/index'
const store = useCounterStore()

const $router = useRouter()
const $route = useRoute()

const optionAc = ref('video')

const optionArr = ref([])

const search = ref('')

const visible = ref(false)

const token = ref(null)

const userData = ref({
    avatar: "",   // 头像地址
    nickname: ""   // 昵称
})

onMounted(() => {
    // 获取分类的类型列表
    categoryList().then(data => {
        optionArr.value = data.data
    })

    // 从 localStorage 中读取数据
    // 如果本地存储中存在 Authorization，则将其赋值给 token.value，否则保持原值
    token.value = localStorage.getItem('Authorization') || token.value;

    // 如果 token.value 存在
    if (token.value) {
        // 获取用户信息
        getUserInfo().then(res => {
            // 如果返回的 code 等于 0，表示成功获取用户信息
            if (res.code === 0) {
                // 设置关注数量和粉丝数量
                store.setFollowCount(res.data.followCount)
                store.setFollowerCount(res.data.followerCount)

                // 设置 userData.value 对象的属性
                userData.value = {
                    avatar: res.data.avatar,     // 头像地址
                    nickname: res.data.nickname  // 昵称
                }
            }
        })
    }
})

// 切换分类
const onOption = (categoryId, type) => {
    const thisPath = $route.path
    const judgmentArr = ['followlist', 'collectlist', 'publish']

    if (judgmentArr.includes(type)) {
        // 如果 type 在 judgmentArr 中
        $router.push({
            name: type,
        })

        let count = 0; // 计数器

        // 定义定时器，每100毫秒执行一次
        const intervalId = setInterval(() => {
            // 如果路径发生变化，表示页面已切换完成
            if (thisPath !== $route.path) {
                optionAc.value = categoryId
                clearInterval(intervalId);
                return
            }

            count++; // 增加计数器

            if (count === 7) {
                clearInterval(intervalId); // 达到7次后清除定时器
            }
        }, 100);
    } else {
        // 如果 type 不在 judgmentArr 中
        optionAc.value = categoryId

        if (categoryId === 'video') {
            $router.push({
                name: type
            })
        } else {
            $router.push({
                name: type,
                query: {
                    categoryId
                }
            })
        }
    }
}

// 判断搜索框是否聚集
const focusClass = ref(false)

// 搜索框聚焦事件
const focusSearchTrue = () => {
    focusClass.value = true
}

// 搜索框失焦事件
const focusSearchFalse = () => {
    focusClass.value = false
}

// 搜索框回车事件
const onInput = () => {
    $router.push({
        name: 'searchlist',
        query: {
            keyword: search.value
        }
    })
}

// 遮罩层
const overflow = ref(null)
// 登录弹窗
const loginflow = ref(null)
// 登录弹窗事件
const open = () => {
    // 开启遮罩
    overflow.value.style.display = 'block'
    loginflow.value.style.display = 'block'
}

// 关闭遮罩
const hideOverlay = () => {
    overflow.value.style.display = 'none'
    loginflow.value.style.display = 'none'
}

// 判断当前显示的卡片类型 登录|注册
const isRegister = ref(false)

const onRegisterOrLogin = (type) => {
    if (type == "Register") {
        isRegister.value = true
        return
    }
    isRegister.value = false
}

const username_login = ref("")
const password_login = ref("")

// 登录事件
const onLogin = () => {
    // 构建请求数据
    const data = {
        username: username_login.value,
        password: password_login.value,
    }

    // 发起登录请求
    login(data).then(res => {
        // 如果返回的 code 等于 0，表示登录成功
        if (res.code === 0) {
            ElMessage({
                duration: 3000,
                message: '登录成功',
                type: 'success',
            })

            // 将登录成功后返回的 token 存储到 localStorage 中
            localStorage.setItem('Authorization', `Bearer ${res.data}`)

            // 隐藏覆盖层
            hideOverlay()

            // 刷新页面
            window.location.reload();
        } else {
            // 如果返回的 code 不等于 0，表示登录失败
            ElMessage({
                duration: 3000,
                message: res.msg,
                type: 'error',
            })
        }
    })
}

// 退出登录事件
const quitLogin = () => {
    visible.value = false

    // 从 localStorage 中删除 token
    localStorage.removeItem('Authorization')

    if ($route.path === '/video') {
        // 如果当前路径是 '/video'，则刷新页面
        window.location.reload()
    } else {
        // 否则，跳转到首页并刷新页面
        $router.push({
            name: 'home',
            query: {
                refresh: true
            }
        })
    }
}

const username = ref("")
const password = ref("")
const passwordConfirm = ref("")

// 注册事件
const onEnroll = () => {
  // 构建请求数据
  const data = {
    username: username.value,
    password: password.value,
    passwordConfirm: passwordConfirm.value
  }

  // 发起注册请求
  register(data).then(res => {
    // 如果返回的 code 等于 0，表示注册成功
    if (res.code === 0) {
      ElMessage({
        duration: 3000,
        message: '注册成功',
        type: 'success',
      })
      
      // 调用 onRegisterOrLogin 方法，参数为 'login'，执行登录操作
      onRegisterOrLogin('login')
    } else {
      // 如果返回的 code 不等于 0，表示注册失败
      ElMessage({
        duration: 3000,
        message: res.msg,
        type: 'error',
      })
    }
  })
}
</script>

<style scoped>
p {
    margin: 0;
    padding: 0;
}

.box-max {
    width: 99vw;
    height: 97vh;
    display: flex;
    flex-direction: column;
    padding: 0.4rem;
    box-sizing: border-box;
}

.box-top {
    height: 7%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 0.4rem;
}

.box-input {
    width: 44%;
    display: flex;
    justify-content: center;
    padding-left: 12%;
}

.box-user-max {
    width: 28%;
    display: flex;
    align-items: center;
    justify-content: end;
    padding-right: 1%;
}

.box-log {
    width: 26%;
    display: flex;
    align-items: center;
    padding-left: 2%;
    box-sizing: border-box;
}

.user-image {
    width: 3rem;
    height: 3rem;
    border-radius: 50%;
    display: flex;
}

.input {
    width: 100%;
    height: 1.8rem;
    transition: width 1s;
    padding: 0.5rem 0;
    padding-left: 1rem;
    padding-right: 0.5rem;
    border-radius: 3rem;
    display: flex;
    align-items: center;
}

.search-s {
    width: 94%;
    background-color: rgba(253, 253, 253, 0);
    color: rgba(0, 0, 0, 0.6);
    font-weight: 600;
    list-style: none;
    box-shadow: none;
    outline: none;
    border-style: none;
}

.focus-input {
    width: 100%;
    height: 2.5rem;
    transition: width 1s;
    color: rgba(0, 0, 0, 0.8);
}

.search-icon {
    width: 2rem;
    height: 2rem;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #626aef;
    color: white;
    cursor: pointer;
}

.box-log>p {
    font-size: 1.6rem;
}

.box-body {
    height: 90%;
    width: 100%;
    display: flex;
}

.box-left {
    width: 14%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box;
}

.box-user {
    width: 100%;
    display: flex;
    flex-direction: column;
    flex-wrap: wrap;
    padding: 0 1rem 0 0;
}

.scrollbar-option {
    min-height: 43vh;
    height: 43vh;
    padding: 0 0.6rem 0 0;
}

.option {
    position: relative;
    box-sizing: border-box;
    height: 9vh;
    width: 100%;
}

.option .icon {
    margin-right: 0.7rem;
}

.option>div {
    height: 80%;
    width: 88%;
    border-radius: 0.9rem;
    cursor: pointer;
}

.option-ac {
    position: absolute;
    right: 8%;
    color: white;
    background: linear-gradient(145deg, #585fd7, #6971ff);
    box-shadow: 0.4rem 0.4rem 0.4rem #c1c1c1,
        -0.4rem -0.4rem 0.4rem #ffffff;
}

.option-ac .icon {
    color: white;
}

.option-nc {
    position: absolute;
    right: 4%;
    background: linear-gradient(145deg, #eeeeee, #ffffff);
    box-shadow: 0.4rem 0.4rem 0.4rem #e3e3e3,
        -0.4rem -0.4rem 0.4rem #ffffff;
    color: rgba(58, 58, 58, 0.713);
    transition: color 0.4s;
    /* 过渡属性和时间 */
    transition: right 0.4s;
    /* 过渡属性和时间 */
}

.option-nc:hover {
    right: 8%;
    color: white;
    background: linear-gradient(145deg, #585fd7, #6971ff);
    box-shadow: 0.4rem 0.4rem 0.4rem #c1c1c1,
        -0.4rem -0.4rem 0.4rem #ffffff;
    transition: color 0.2s;
    /* 过渡属性和时间 */
    transition: right 0.4s;
    /* 过渡属性和时间 */
}

.box-sort {
    width: 100%;
    height: 70%;
}

.box-video {
    width: 86%;
    height: 100%;
}

.log-in {
    width: 8rem;
}

/* 遮罩层样式 */
.overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.3);
    /* 半透明黑色背景 */
    z-index: 2;
    /* 确保遮罩层显示在其他元素之上 */
    display: none;
    /* 初始状态下隐藏 */
    align-items: center;
    justify-content: center;
}

/* 登录框 */
.box-login {
    width: 50%;
    height: 60%;
    border-radius: 2rem;
    background-color: white;
    box-shadow: 0.4rem 0.4rem 0.4rem rgba(149, 149, 149, 0.5);
    position: absolute;
    display: none;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
    z-index: 3;
    top: 15%;
    left: 25%;
    color: rgba(0, 0, 0, 0.6);
}

.box-login>div {
    height: 100%;
}

.box-login .title {
    color: #626aef;
}

.box-login .input>p {
    margin: 0;
    padding: 0;
}

.box-login .input {
    width: 70%;
}

.login {
    display: flex;
    flex-direction: row;
    background-color: rgba(229, 236, 245, 0.5);
}

.login-l {
    width: 45%;
    padding-top: 7%;
    display: flex;
    align-items: center;
    flex-direction: column;
    background-color: white;
}

.login-r {
    width: 55%;
    padding-top: 14%;
    display: flex;
    align-items: center;
    flex-direction: column;
}

.login-lottie {
    position: absolute;
    top: 0;
    z-index: 1;
}

.login-r-btn {
    margin-top: 5%;
}

.btn {
    width: 100%;
    height: 6rem;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.btns {
    width: 100%;
    margin-top: 1rem;
}

.el-btn {
    width: 100%;
    height: 2rem;
}

.white-8 {
    background-color: #626aef;
    color: rgba(255, 255, 255, 0.8);
}

.back-login {
    color: #626aef;
    cursor: pointer;
}

.box-user-data {
    display: flex;
    align-items: center;
}

.box-user-data>div {
    margin-left: 1rem;
}

.animation-left {
    position: absolute;
    left: 20%;
    animation: animation-left 0.6s infinite alternate-reverse ease-in-out;
}

@keyframes animation-left {
    from {
        left: 18%;
    }

    to {
        left: 21%;
    }
}

.animation-right {
    position: absolute;
    right: 20%;
    animation: animation-right 0.6s infinite alternate-reverse ease-in-out;
}

@keyframes animation-right {
    from {
        right: 16%;
    }

    to {
        right: 19%;
    }
}


.animation-right {
    position: absolute;
    right: 20%;
}

.color-theme {
    color: #626aef;
    cursor: pointer;
}
</style>